(function (window) {
    var db = window.openDatabase('chatDB', '1.0', '聊聊数据库', 1024 * 1024);
    var setCreated = window.dataManager.set('dbCreated');
    var getCreated = window.dataManager.get('dbCreated');

    if (!getCreated()) {
        // 创建数据表
        db.transaction(function (tx) {
            tx.executeSql(['CREATE TABLE IF NOT EXISTS dialogue(',
                    '_id TEXT  PRIMARY KEY ,',
                    'mid TEXT ,',
                    'uid TEXT ,',
                    'name TEXT ,',
                    'type TEXT ,',
                    'msg TEXT ,',
                    'time TEXT,',
                    'reciever TEXT)'
                ].join(''), [],
                function () {
                    console.log('创建消息表成功.');
                },
                function () {
                    console.log('创建消息表失败.');
                });
            tx.executeSql(['CREATE TABLE IF NOT EXISTS friend(',
                    'uid TEXT ,',
                    'fid TEXT ,',
                    'state TEXT ,',
                    'sid TEXT ,',
                    'name TEXT ,',
                    'photoid TEXT ,',
                    'photo TEXT,',
                    'kefu TEXT)'
                ].join(''), [],
                function () {
                    console.log('好友表创建成功.');
                },
                function () {
                    console.log('好友表创建失败.');
                });
        });
        setCreated(true);
    }
    /**
     * 处理参数，例如 {name:'zhangsan',age:56} => " where 1=1 and name='zhangsan' and age=56"
     * @param params
     * @returns {{append: string, fill: Array}}
     */
    function resolveCondition(params) {
        var paramArr = [],
            append = ' where 1=1';
        Object.keys(params).forEach(function (key) {
            paramArr.push(params[key]);
            append += ' and ' + key + '=?';
        });
        return {
            append: append,
            fill: paramArr
        };
    }

    /**
     * model构造函数，主要提供增删改查
     * @param tableName 表名称
     * @param fields 列名称数组
     * @constructor
     */
    function Model(tableName, fields) {
        this.tableName = tableName;
        this.fields = fields;
        this.fieldStr = fields.join(',');
    }

    Model.prototype = {
        constructor: Model,
        /**
         * 插入数据
         * @param info  info  必须和fields一一对应上
         * @param callback
         */
        insert: function (info, callback) {
            var me = this;
            db.transaction(function (tx) {
                var fields = me.fields.map(function () {
                    return '?';
                }).join(',');

                tx.executeSql('insert into ' + me.tableName + '(' + me.fieldStr + ') values (' + fields + ')',
                    info,
                    function () {
                        callback && callback(0);
                    },
                    function () {
                        callback && callback(1, 'insert error');
                    });
            });
        },
        query: function (params, callback) {
            var me = this,
                condition = resolveCondition(params);
            var sql = 'select * from ' + me.tableName + condition.append;
            db.transaction(function (tx) {
                tx.executeSql(sql, condition.fill, function (tx, res) {
                    var length = res.rows.length,
                        result = [];
                    for (var i = 0; i < length; i++) {
                        result.push(res.rows.item(i));
                    }
                    callback && callback(0, result);
                }, function () {
                    callback && callback(1, 'query error');
                });
            });
        },
        remove: function (params, callback) {
            var me = this,
                condition = resolveCondition(params);
            var sql = 'delete from ' + me.tableName + condition.append;
            db.transaction(function (tx) {
                tx.executeSql(sql, condition.fill, function () {
                    callback && callback(0);
                }, function () {
                    callback && callback(1, 'remove error');
                });
            });
        },
        clear: function (callback) {
            this.remove({}, callback);
        }
    };

    window.DbModel = Model;
})(window);